package com.swak.excel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import com.swak.excel.random.RandomData;
import com.swak.excel.random.RandomSheet;
import com.swak.utils.FileUtils;
import com.swak.utils.IOUtils;
import com.swak.utils.Lists;
import com.swak.utils.StringUtils;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * 随机的写文件并导出
 * 
 * @author 618lf
 */
@Getter
@Setter
@Accessors(chain = true)
public class RandomExporter {

	private static Logger logger = LoggerFactory.getLogger(RandomExporter.class);

	/**
	 * 模板默认的路径
	 */
	private static String templatePath = "classpath:/excel/";

	private File outDir;
	private String template;
	private List<RandomSheet> sheets = Lists.newArrayList();

	public RandomExporter() {
		outDir = FileUtils.tempFile("downloads");
	}

	public RandomExporter addSheet(RandomSheet sheet) {
		sheets.add(sheet);
		return this;
	}

	public File out() {
		Assert.isTrue(StringUtils.isNotBlank(template), "请指定模板！");

		/*
		 * 读取模板文件
		 */
		InputStream templateFile = FileUtils.resource(templatePath + template);

		/*
		 * 输出到一个临时的文件中
		 */
		File outFile = FileUtils.touchFile(outDir, UUID.randomUUID().toString() + "_" + template);
		FileOutputStream out = null;
		try {
			Workbook template = ExcelUtils.load(templateFile);
			this.doOut(template);
			out = FileUtils.out(outFile);
			template.write(out);
		} catch (IOException e) {
			logger.error("导出文件异常", e);
		} finally {
			IOUtils.closeQuietly(out);
		}
		return outFile;
	}

	private void doOut(Workbook template) {
		for (RandomSheet rs : sheets) {
			try {
				Sheet sheet = template.getSheetAt(rs.getIndex());
				if (sheet == null) {
					return;
				}

				List<RandomData> datas = rs.getDatas();
				for (RandomData rd : datas) {
					Row row = sheet.getRow(rd.getRow());
					if (row == null) {
						row = sheet.createRow(rd.getRow());
					}
					Cell cell = row.getCell(rd.getCell());
					if (cell == null) {
						cell = row.createCell(rd.getCell());
					}
					writeCell(cell, rd.getValue());
				}
				
				/*
				 * 让公式自动执行
				 */
				sheet.setForceFormulaRecalculation(true);
			} catch (Exception e) {
				logger.error("导出文件异常", e);
			}
		}
	}

	/**
	 * 根据实际的类型写文件
	 * 
	 * @param cell
	 * @param value
	 */
	private void writeCell(Cell cell, Object value) {
		if (cell == null || value == null) {
			return;
		}

		if (value instanceof String) {
			cell.setCellValue((String) value);
		} else if (value instanceof BigDecimal) {
			cell.setCellValue(((BigDecimal) value).doubleValue());
		} else if (value instanceof LocalDate) {
			cell.setCellValue((LocalDate) value);
		} else if (value instanceof LocalDateTime) {
			cell.setCellValue((LocalDateTime) value);
		} else if (value instanceof Boolean) {
			cell.setCellValue((Boolean) value);
		} else if (value instanceof Date) {
			cell.setCellValue((Date) value);
		} else if(value instanceof Byte) {
			cell.setCellValue(String.valueOf(value));
		}
	}

	public static RandomExporter of() {
		return new RandomExporter();
	}
}